﻿
(function (app) {
    app.service('sopservice', function ($q) {
        //Function to read all records
        this.get = function () {
            var deferred = $q.defer();
            //Get the SharePoint Context object based upon the URL
            var ctx = new SP.ClientContext(appWebUrl);
            var appCtxSite = new SP.AppContextSite(ctx, hostWebUrl);
            var web = appCtxSite.get_web(); //Get the Web 
            var list = web.get_lists().getByTitle("CategoryList"); //Get the List
            var query = new SP.CamlQuery(); //The Query object. This is used to query for data in the List
            query.set_viewXml('<View><RowLimit></RowLimit>10</View>');
            var items = list.getItems(query);
            ctx.load(list); //Retrieves the properties of a client object from the server.
            ctx.load(items);

            //Execute the Query Asynchronously
            ctx.executeQueryAsync(
                Function.createDelegate(this, function () {
                    var itemInfo = '';
                    var enumerator = items.getEnumerator();
                    var CategoryArray = [];

                    while (enumerator.moveNext()) {
                        var currentListItem = enumerator.get_current();
                        CategoryArray.push({
                            ID: currentListItem.get_item('ID'),
                            CategoryId: currentListItem.get_item('Title'),
                            CategoryName: currentListItem.get_item('CategoryName')
                        });
                    }
                    deferred.resolve(CategoryArray);
                }),
                Function.createDelegate(this, function (sender, args) {
                    deferred.reject('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
                })
                );
            return deferred.promise;
        };
    })
}(angular.module('sopmodule')));

